package homework1;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

public class User 
{
	private String name,address,job;
	private int id;
	//private ArrayList<Card> ownCards;
	
	
	private User(String name,String address,String job)
	{
		this.name=name;
		this.address=address;
		this.job=job;
	}
	
	
	
	private void saveUser()//保存用户到数据库
	{
		
	}
	
	public static String formatID(int id)
	{
		if(id<=9) return "00"+id;
		if(id<=99) return "0"+id;
		return ""+id;
	}
	
	public static int getUserID(String name)//查找用户，返回值大于0表示id，否则表示没有找到
	{
		try {
			Statement stmt = DataBaseController.getDBConnecter().connection.createStatement();
			String sql="select * from USER where USER_NAME='"+name+"'";
			ResultSet rs=stmt.executeQuery(sql);
			ResultSetMetaData m=rs.getMetaData();
			rs.last();
			if(rs.getRow()<=0) return 0;
			rs.beforeFirst();
			rs.next();
			return rs.getInt("ID");
		} catch (SQLException e) 
		{
			return -1;
		} 
	}
	
	public static User getUser(String name)//查找用户，没有用到，还没有实现
	{
		return null;
	}
	
	public static int createUser(String name,String address,String job)//创建用户，返回正数表示id，否则为错误码,-1表示姓名重复
	{
		if(getUserID(name)>0)
		{
			return 0;
		}
		else
		{
			try 
			{
				Statement stmt = DataBaseController.getDBConnecter().connection.createStatement();
				String sql="INSERT INTO USER (USER_NAME, Address, JOB) VALUES ('"+name+"', '"+address+"','"+job+"')";
				boolean rs=stmt.execute(sql);
				return getUserID(name);
			} catch (SQLException e) 
			{
				e.printStackTrace();
				return -1;
			} 
		}
	}
	

	
	public static String getCreateUserWrong(int id)//获取创建用户出错信息
	{
		return "已存在的用户名";
	}
	

}
